package com.heima.gateway.filer;

import com.heima.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
@Service
@Slf4j
public class AuthFailer implements GlobalFilter, Ordered {
//    这个是拦截登录请求的
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        首先获得请求响应和请请求路径
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
//        在此判断请求路径里是不是有login
        if(path.contains("/login")){
//            有的话直接转发给后端
           return chain.filter(exchange);

        }
//        如果没有获得token
        String token = request.getHeaders().getFirst("token");
        if(token!=null){
        try {
            //            不等于空的华解析token并判断他的状态
            Claims claims = AppJwtUtil.getClaimsBody(token);
//            获得他的状态 0和-1 是有效的
            int i = AppJwtUtil.verifyToken(claims);
            if(i==0||i==-1){
                Object userId = claims.get("userId");
                request.mutate().header("userId",userId.toString());
                return chain.filter(exchange);
            }

        }catch (Exception e){

            log.error(e.getMessage());

            }

        }
//        没有token则返回401没授权的状态
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
//
        return response.setComplete();
    }
//优先级的不用改
    @Override
    public int getOrder() {
        return 0;
    }
}
